<?php

namespace App\Http\Middleware;

use Closure;

class Jwt
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next,$type)
    {
        $jwtConfig = config('my.jwt');

        //jwt白名单
        $able_url = ['api/*/login','api/stu/pwd'];
        foreach($able_url as $k=>$v){
            if($request->is($v)){
                //直接通过中间件
                return $next($request);
            }
        }

        //判断是不是login路由
		if(!$request->is('api/*/login')){
            $token =  $request->header('token');
            $arr = explode('.',$token);

            if(count($arr)<3){
                die(json_encode(['error'=>'非法操作']));
            }
            $header = $arr[0];
            $playload = $arr[1];
            $signature = $arr[2];

            //加密
            $jwt = hash_hmac($jwtConfig['type'],($header.".".$playload),$jwtConfig['key']);

            if($signature != $jwt){
                die(json_encode(['error'=>'非法操作']));
            }else{
                $playloadJson = json_decode(base64_decode($playload),TRUE);
                $validtime = $playloadJson['validtime'];
                if($validtime < time()){
                    die(json_encode(['error'=>'用户身份过期']));
                }
            }

            //判断token的类型和中间键匹配的类型是否相同
            if($playloadJson['usertype']!=$type && $type != 'all'){
                die(json_encode(['error'=>'偷来的token？']));
            }
            //存储当前登录的账号
            $request->login_username = $playloadJson['playload'];
        }
        return $next($request);
    }
}
